<template>
	<a-modal
		:visible="props.visible"
		title="添加协作人"
		:width="600"
		@cancel="emits('update:visible', false)"
		@ok="confirmAdd"
	>
		<a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '100px' } }" class="form_label">
			<a-form-item label="选择协作人" name="tempPersonIds">
				<a-tree-select
					v-model:value="form.tempPersonIds"
					style="width: 360px"
					:tree-data="orgUserTreeData"
					tree-checkable
					allow-clear
					:show-checked-strategy="SHOW_PARENT"
					placeholder="请选择人员范围"
					tree-node-filter-prop="label"
					:fieldNames="fieldNames"
					max-tag-count="responsive"
					:dropdownMatchSelectWidth="false"
					treeNodeFilterProp="name"
					@change="onPersonChange"
				/>
			</a-form-item>
		</a-form>
	</a-modal>
</template>
<script setup>
	import customerApi from '@/api/biz/customerApi'
	import { globalStore } from '@/store'
	import { TreeSelect } from 'ant-design-vue'
	import tool from '@/utils/tool'

	const store = globalStore()

	const props = defineProps({
		visible: {
			type: Boolean,
			default: false
		},
		customerCode: {
			type: String
		},
		ownerId: {
			type: String,
			required: true
		},
		/**
		 * 获取协作人列表
		 */
		getCollaboratorList: {
			type: Function,
			default: () => {}
		}
	})
	const emits = defineEmits(['update:visible', 'finished'])

	watch(
		() => props.visible,
		(newVal, oldVal) => {
			if (newVal) {
				props
					.getCollaboratorList({
						code: props.customerCode
					})
					.then((res) => {
						const disableIds = res.map((item) => 'e_' + item.concertId)
						disableIds.push('e_' + props.ownerId)
						orgUserTreeData.value = store.disableDeptList(disableIds)
					})
			}
		},
		{
			immediate: true
		}
	)

	const SHOW_PARENT = TreeSelect.SHOW_PARENT
	const fieldNames = {
		label: 'name',
		value: 'id'
	}
	const orgUserTreeData = ref([])
	const personIds = ref([])
	const onPersonChange = (value, label, extra) => {
		personIds.value = tool.getAllBottomPersonIds(extra.allCheckedNodes)
	}

	const form = ref({
		tempPersonIds: []
	})

	const rules = {
		tempPersonIds: [{ required: true, type: 'array', message: '请选择协作人', trigger: 'blur' }]
	}
	const formRef = ref()
	const confirmAdd = () => {
		formRef.value.validate().then(() => {
			customerApi
				.addCollaboratorOrTransfer({
					customerCode: props.customerCode,
					type: 0,
					userId: personIds.value.join(',')
				})
				.then(() => {
					emits('update:visible', false)
					emits('finished')
				})
		})
	}
</script>
<style lang="less" scoped>
	.form_label :deep(.ant-form-item-label > label) {
		color: rgb(107 114 128);
	}
	.form_label :deep(.ant-form-item-label > label::after) {
		color: transparent;
	}
</style>
